package maven;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import maven.diy.HandleResult;
import maven.excel.RefExcelDto;
import maven.excel.ExcelWriterHelper;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author 史祥连
 * @Date 2024/2/1 17:46
 * @Version 1.0
 */
public class AnalysisResult {

    public static void main(String[] args) {
        HandleResult handleResult = new HandleResult(0, "weaver-ebuilder-form");
        List<String> arrays = Arrays.asList("weaver-ebuilder-form-ai", "weaver-ebuilder-form-analysis", "weaver-ebuilder-form-base", "weaver-ebuilder-form-core", "weaver-ebuilder-form-service", "weaver-ebuilder-form-view");
        List<TreeNode> allChildren = new ArrayList<>();
        for (String jarname : arrays) {
            handleResult.setCurTopProjectName(jarname);
            TreeNode treeNode = handleResult.getTreeNode(jarname);
            allChildren.addAll(treeNode.getAllChildren(true));
        }

        //这里过滤的jar没有去重
        List<TreeNode> analysis = filter(allChildren, (s -> s.filter(k -> k.getKbSize() != null && k.getKbSize() > 1024 * 5)));
        Map<Long, TreeNode> id2TreeNodeMap = allChildren.stream().collect(Collectors.toMap(TreeNode::getId, s -> s));
        ExcelWriterHelper excelWriter = new ExcelWriterHelper("C:\\Datas\\E10\\dev\\Demo\\test5.xlsx");
        excelWriter.loadEasyExcelWrite();
        for (TreeNode node : analysis) {
            System.out.println("size:" + formatSize(node.getKbSize()));
            Map<String, String> result = new HashMap<>();
            WriteSheet writeSheet = EasyExcel.writerSheet(node.formatSheetName()).build();
            excelWriter.print(node, "", id2TreeNodeMap, new ArrayList<>(), result, writeSheet);
        }
        //使用easyexcel写入完成，下面开始使用POI进行追加
        excelWriter.getExcelWriter().finish();
        LinkedHashMap<String,TreeNode> containsSet = new LinkedHashMap<>();
        for (TreeNode treeNode : analysis) {
            containsSet.put(treeNode.formatSheetName(),treeNode);
        }
        List<TreeNode> list = new ArrayList<>();
        for (Map.Entry<String, TreeNode> stringTreeNodeEntry : containsSet.entrySet()) {
            list.add(stringTreeNodeEntry.getValue());

        }
        excelWriter.appendLinkInfo(list);
        analysisResult(analysis, allChildren);
    }

    private static void analysisResult(List<TreeNode> analysis, List<TreeNode> allChildren) {
        Map<String, List<TreeNode>> groupedByNodeId = analysis.stream()
                .collect(Collectors.groupingBy(s -> s.getGroup() + ":" + s.getJarName()));
        for (Map.Entry<String, List<TreeNode>> entry : groupedByNodeId.entrySet()) {
            List<TreeNode> value = entry.getValue();
            System.out.println("value = " + value);
        }
        String projectPath = System.getProperty("user.dir");
    }

    private static Map<String, List<RefExcelDto>> format(Map<String, List<TreeNode>> groupedByNodeId, List<TreeNode> allChildren) {
        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        return null;
    }


    private static void writeExcel(String filePath, Map<String, List<RefExcelDto>> excelData) {

        // 创建 ExcelWriterBuilder
        ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(filePath, RefExcelDto.class);

        // 完成写入，关闭 ExcelWriter
        excelWriterBuilder.build().finish();
    }

    /**
     * 根据规则过滤，给出全部符合条件的结果
     * 同时打印符合条件结果的引用链路
     *
     * @param allChildren
     * @return
     * @author 史祥连
     * @date 2024/2/2-10:03
     * @version 1.0
     */
    private static List<TreeNode> filter(List<TreeNode> allChildren, Filter filter) {
        List<TreeNode> resultTreeNode;
        if (filter != null) {
            resultTreeNode = filter.filter(allChildren.stream()).collect(Collectors.toList());

        } else {
            resultTreeNode = allChildren.stream().sorted((a, b) -> Math.toIntExact(b.getKbSize() - a.getKbSize()))
                    //打印最大的
                    .filter(s -> s.getKbSize() > 1024 * 10)
                    .collect(Collectors.toList());
        }
        return resultTreeNode;
    }

    interface Filter {

        Stream<TreeNode> filter(Stream<TreeNode> treeNodes);

    }


    public static void print(TreeNode curTreeNode, String prefix, Map<Long, TreeNode> treeNodeMap, List<String> printList, Map<String, String> result) {
        String pr = curTreeNode.getGroup() + ":" + curTreeNode.getJarName();
        printList.add(prefix + pr);
        Long parentId = curTreeNode.getParentId();
        if (parentId != null) {
            TreeNode treeNode = treeNodeMap.get(parentId);
            print(treeNode, prefix, treeNodeMap, printList, result);
        } else {
            StringBuilder sb2 = new StringBuilder();
            for (int i = printList.size() - 1; i >= 0; i--) {
                StringBuilder sb = new StringBuilder();
                for (int i1 = (printList.size() - i - 1); i1 > 0; i1--) {
                    sb.append("   ");
                }
                String all = sb + printList.get(i);
                sb2.append(all).append("\n");
                System.out.println(all);
            }
            result.put(curTreeNode.getGroupJarName(), sb2.toString());
        }

    }

    public static String formatSize(long size) {
        BigDecimal bigDecimal = new BigDecimal(size);
        BigDecimal divide = bigDecimal.divide(new BigDecimal(1024));
        return divide.toPlainString() + "MB";
    }
}
